package com.houdoudou.supplier.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.conn.ClientConnectionOperator;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.houdoudou.supplier.R;
import com.houdoudou.supplier.SupplierMainActivity;
import com.houdoudou.supplier.bean.Distribute;
import com.houdoudou.supplier.bean.Machine;
import com.houdoudou.supplier.bean.Order;
import com.houdoudou.supplier.bean.OrderProduct;
import com.houdoudou.supplier.bean.Supplier;
import com.houdoudou.supplier.common.CommonFunction;
import com.houdoudou.supplier.common.Constant;
import com.houdoudou.supplier.common.DateTimeFunction;
import com.houdoudou.supplier.common.MyAlert;
import com.houdoudou.supplier.common.UniversalHttpPost;
import com.houdoudou.supplier.common.ZebraPrinter;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Space;
import android.widget.TextView;
import android.widget.Toast;

public class CurrentOrderFrg  extends Fragment{

	JSONArray ordersJA= new JSONArray();
	JSONObject searchOrderJO=  new JSONObject();
	int COCid=0; //当前分类编号
	TextView orderAll,orderCanceled,orderPayid,orderToPay,orderAccepted,orderToAccept,orderRefused;
	TextView orderShiped,orderToship,orderRefunded,orderArrived,orderToArrive;
	TextView orderReceived,orderToReceive,orderToRetake,orderRetaked,orderAbandomed;
	TextView orderToMachine, orderMachined,orderPrinted,orderToPrint;
	ProgressBar prgs;
	TextView resultHint,date;
	Button refresh,function1,function2,confirmDate;
	Spinner sp_machine,sp_timeFlag;
	ImageView img_calendar;
	// CalendarView calendarView;
	DatePicker datePicker;
	ListView orderListView;
	CheckBox chooseall;
	LinearLayout lt_datePicker;
	View.OnClickListener myClickListenr;
	AdapterView.OnItemSelectedListener machineSelectedListener,timeFlagSelectedListemer;
	private String PULLCURRENTORDER="searchOrder";
	private String SEARCHDISTRIBUTE="searchDistribute";
	private String ACCEPTORDER="acceptOrder";
	private String REFUSEORDER="refuseOrder";
	private String AFFAIR_PRINTORDER="printOrder";
	private String SHIPORDER="shipOrder";
	private String ISSELECTED="isSelected";
	int array_machine_id[]= new int[100];
	List<String> sp_machine_data= new ArrayList<String>();
	boolean isOrderListVailble=false,needPullMachine=true; //isCalendarViewShowing=false, 
	OrderListAdapter orderListAdapter;
	static final int ALL=0,CANCELED=1,PAID=2,TOPAY=3,REFUSED=4,ACCEPTED=5,TOACCEPT=6;
	static final int REFUNDED=7,SHIPED=8,TOSHIP=9,ARRIVED=10,TOARRIVE=11,RECEIVED=12,TORETAKE=13,TORECEIVE=14;
	static final int ABANDOMED=15,RETAKED=16,PRINTED=17,TOPRINT=18,TOMACHINE=19,MACHINED=20;
 	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		 View view =inflater.inflate(R.layout.frg_currentorder, container, false);
		 init_listener();
		 init_component(view);
		 searchOrderJO.put(Order.SUPPLIERTELNUM, Constant.supplierJO.getString(Supplier.TELNUM)); 
		 date.setText("请选择日期>>");
		 prgs.setVisibility(View.INVISIBLE);
		 resultHint.setText("");
		 orderAll.performClick();
		 return view;
	}

	private void pullCurrentOrder(){
		
		if(!searchOrderJO.containsKey(Order.TIMEFLAG)){ 
			Toast.makeText(getActivity(), "请选择班次，再操作", Toast.LENGTH_SHORT).show();return;}
		if(!searchOrderJO.containsKey(Order.DATEAA)){ 
			Toast.makeText(getActivity(), "请选择日期，再操作", Toast.LENGTH_SHORT).show();return;}
		prgs.setVisibility(View.VISIBLE);
		String[] params= new String[3];
        params[0]=Constant.BaseUrl+Constant.SupplierUrl;
        params[1]=PULLCURRENTORDER; //PostCode  
        JSONObject jsonData= new JSONObject();
        jsonData.put("supplier", Constant.supplierJO);
        jsonData.put("order", searchOrderJO);
        params[2]=jsonData.toString();
        new HttpPostTaskforPollCurrentOrder().execute(params);
        
        String[] params2= new String[3];
        params2[0]=Constant.BaseUrl+Constant.SupplierUrl;
        if(needPullMachine){
        	  params2[1]=SEARCHDISTRIBUTE; //PostCode  	
        	  JSONObject distributeJO= new JSONObject();
        	  distributeJO.put(Distribute.SUPPLIER, Constant.supplierJO.getString(Supplier.TELNUM));
        	  distributeJO.put(Distribute.TIMEFLAG,searchOrderJO.getInt(Order.TIMEFLAG));
        	  jsonData.put("distribute", distributeJO);
        	  params2[2]=jsonData.toString();
         new HttpPostTaskforPollCurrentOrder().execute(params2);
        }
        
	}
	private void init_listener(){
		myClickListenr= new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(v==refresh){ pullCurrentOrder();}
				if(v==orderAll)        {  COCid=ALL; clearAllOrderClassifySelected(); orderAll.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged(); function1.setVisibility(View.GONE); function2.setVisibility(View.GONE); return; } //orderAll
				if(v==orderCanceled)   {  COCid=CANCELED; clearAllOrderClassifySelected(); orderCanceled.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged(); function1.setVisibility(View.GONE); function2.setVisibility(View.GONE);  return; } //orderAll
				if(v==orderPayid)      {  COCid=PAID; clearAllOrderClassifySelected(); orderPayid.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged(); function1.setVisibility(View.GONE); function2.setVisibility(View.GONE); return; } //orderAll
				if(v==orderToPay)      {  COCid=TOPAY;  clearAllOrderClassifySelected(); orderToPay.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged(); function1.setVisibility(View.GONE); function2.setVisibility(View.GONE); return; } //orderAll
				if(v==orderRefused)    {  COCid=REFUSED; clearAllOrderClassifySelected(); orderRefused.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged(); function1.setVisibility(View.GONE); function2.setVisibility(View.GONE); return;  } //orderAll
				if(v==orderAccepted){  COCid=ACCEPTED; clearAllOrderClassifySelected(); orderAccepted.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged(); function1.setVisibility(View.GONE); function2.setVisibility(View.GONE); return; } //orderAll
				if(v==orderToAccept){  COCid=TOACCEPT; clearAllOrderClassifySelected(); orderToAccept.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged(); function1.setVisibility(View.VISIBLE); function2.setVisibility(View.VISIBLE); function1.setText("接单");  function2.setText("据单"); return; } //orderAll
			//	if(v==orderRefunded){  COCid=REFUNDED; clearAllOrderClassifySelected(); orderRefunded.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged(); return; } //orderAll
				if(v==orderShiped){  COCid=SHIPED; clearAllOrderClassifySelected(); orderShiped.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged(); function1.setVisibility(View.GONE); function2.setVisibility(View.GONE); return; } //orderAll
				if(v==orderToship){  COCid=TOSHIP; clearAllOrderClassifySelected(); orderToship.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged(); function1.setVisibility(View.VISIBLE); function2.setVisibility(View.GONE); function1.setText("发货");  return; } //orderAll
				if(v==orderArrived){  COCid=ARRIVED; clearAllOrderClassifySelected(); orderArrived.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged();function1.setVisibility(View.GONE); function2.setVisibility(View.GONE); return; } //orderAll
				if(v==orderToArrive){  COCid=TOARRIVE; clearAllOrderClassifySelected(); orderToArrive.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged();function1.setVisibility(View.GONE); function2.setVisibility(View.GONE); return; } //orderAll
				if(v==orderReceived){  COCid=RECEIVED; clearAllOrderClassifySelected(); orderReceived.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged();function1.setVisibility(View.GONE); function2.setVisibility(View.GONE); return; } //orderAll
				if(v==orderToRetake){  COCid=TORETAKE; clearAllOrderClassifySelected(); orderToRetake.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged();function1.setVisibility(View.GONE); function2.setVisibility(View.GONE); return; } //orderAll
				if(v==orderToReceive){  COCid=TORECEIVE; clearAllOrderClassifySelected(); orderToReceive.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged();function1.setVisibility(View.GONE); function2.setVisibility(View.GONE); return; } //orderAll
				if(v==orderAbandomed){  COCid=ABANDOMED; clearAllOrderClassifySelected(); orderAbandomed.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged(); function1.setVisibility(View.GONE); function2.setVisibility(View.GONE);return; } //orderAll
				if(v==orderRetaked){  COCid=RETAKED; clearAllOrderClassifySelected(); orderRetaked.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged(); function1.setVisibility(View.GONE); function2.setVisibility(View.GONE);return; } //orderAll
				if(v==orderPrinted){  COCid=PRINTED; clearAllOrderClassifySelected(); orderPrinted.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged();function1.setVisibility(View.VISIBLE); function2.setVisibility(View.GONE);  function1.setText("打印"); return; } 
				if(v==orderToPrint){  COCid=TOPRINT; clearAllOrderClassifySelected(); orderToPrint.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged();function1.setVisibility(View.VISIBLE); function2.setVisibility(View.GONE);  function1.setText("打印"); return; } //orderAll
				if(v==orderToMachine){  COCid=TOMACHINE; clearAllOrderClassifySelected(); orderToMachine.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged();function1.setVisibility(View.GONE); function2.setVisibility(View.GONE); return; } //orderAll
				if(v==orderMachined){  COCid=MACHINED; clearAllOrderClassifySelected(); orderMachined.setBackgroundResource(R.xml.style_blueborder_bluebg); orderListAdapter.notifyDataSetChanged(); function1.setVisibility(View.GONE); function2.setVisibility(View.GONE);return; } //orderAll
				
				if(v==img_calendar||v==confirmDate){
					boolean isShowing= lt_datePicker.isShown();
				 if(isShowing){	  lt_datePicker.setVisibility(View.INVISIBLE);
				      }else{ lt_datePicker.setVisibility(View.VISIBLE);}		 
				    } //img_calendar
				
				if(v==function1){
					if(COCid==TOACCEPT){ //接单
						orderDoSomething(ACCEPTORDER);	
					}
                    if(COCid==TOSHIP){ //发货
                    	orderDoSomething(SHIPORDER);
					}
                    if(COCid==TOPRINT||COCid==PRINTED){ //打印
                    	 JSONArray printOrderJA= new JSONArray();
                  	   for(int i=0;i<ordersJA.getJSONArray(COCid).size();i++){
                  		  if(	ordersJA.getJSONArray(COCid).getJSONObject(i).getBoolean(ISSELECTED)){
                  			 
                  			printOrderJA.add(ordersJA.getJSONArray(COCid).getJSONObject(i));
                  		  }		
                  		}
                  	   
                  	  new ZebraPrinter().printOrders(printOrderJA); 
                  	Dialog dialog = new AlertDialog.Builder(getActivity()).setTitle("确认打印结果")
            	            .setMessage("打印成功？")
            	            .setPositiveButton("成功", new DialogInterface.OnClickListener() {
            	                public void onClick(DialogInterface dialog, int which) {
            	                   orderDoSomething(AFFAIR_PRINTORDER);
            	                }
            	            })
            	            .setNegativeButton("失败", new DialogInterface.OnClickListener() {
            	                public void onClick(DialogInterface dialog, int which) {
            	                   
            	                }
            	            }).create();
            	    dialog.show();
					}
				}
				if(v==function2){
					if(COCid==TOACCEPT){ //据单
						orderDoSomething(REFUSEORDER);
					}
				}
			}
		};
		
		machineSelectedListener= new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
			  if(position==0){
				  if(searchOrderJO.containsKey(Order.MACHINEID)){
					  searchOrderJO.remove(Order.MACHINEID);
					  pullCurrentOrder();
				  }			 
			  }else{
				  searchOrderJO.put(Order.MACHINEID, array_machine_id[position]);
				  pullCurrentOrder();
			  }			
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		};
		
		timeFlagSelectedListemer= new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				 searchOrderJO.put(Order.TIMEFLAG,(position+1));
				 System.out.println("timeFlagSelectedListemer position="+position);
				 needPullMachine=true;
				 pullCurrentOrder();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		};
	
	}
   private JSONArray  packSelectedOrder(String affair ){
	   JSONArray ja= new JSONArray();
	   for(int i=0;i<ordersJA.getJSONArray(COCid).size();i++){
		  if(	ordersJA.getJSONArray(COCid).getJSONObject(i).getBoolean(ISSELECTED)){
			  JSONObject jo= new JSONObject(); 
			  jo.put(Order.ID, ordersJA.getJSONArray(COCid).getJSONObject(i).getLong(Order.ID));
			  if(affair.equals(ACCEPTORDER)){jo.put(Order.STATE, 11);  }
			  if(affair.equals(REFUSEORDER)){jo.put(Order.STATE, 5);  }
			  if(affair.equals(SHIPORDER)){jo.put(Order.STATE, 20);  }
			  if(affair.equals(SHIPORDER)){jo.put(Order.STATE, 20);  }
			  ja.add(jo);
		  }		
		}
	   return ja;
   }
  private void orderDoSomething(String affair){
	  JSONArray dealedOrdersJO= packSelectedOrder(affair);
		 if(dealedOrdersJO.size()==0){
			 MyAlert.simpleDialog(getActivity(), "温馨提示", "请选选择订单，再点操作");
			 return; }
		prgs.setVisibility(View.VISIBLE);
	  String[] params= new String[3];
     params[0]=Constant.BaseUrl+Constant.SupplierUrl;
     params[1]=affair; //PostCode  
     JSONObject jsonData= new JSONObject();
     jsonData.put("supplier", Constant.supplierJO);
     jsonData.put("orders", dealedOrdersJO);
     params[2]=jsonData.toString();
     new HttpPostTaskforPollCurrentOrder().execute(params);
  }	
   
	private void init_component(View view){
		orderAll=(TextView) view.findViewById(R.id.tv_orderall_frgcurrentorder);
		orderCanceled=(TextView) view.findViewById(R.id.tv_ordercancelded_frgcurrentorder);
		orderPayid=(TextView) view.findViewById(R.id.tv_orderpaid_frgcurrentorder);
		orderToPay=(TextView) view.findViewById(R.id.tv_ordertopay_frgcurrentorder);
		orderAccepted=(TextView) view.findViewById(R.id.tv_orderaccepted_frgcurrentorder);
		orderToAccept=(TextView) view.findViewById(R.id.tv_ordertoaccept_frgcurrentorder);
		orderRefused=(TextView) view.findViewById(R.id.tv_orderrefused_frgcurrentorder);
		orderShiped=(TextView) view.findViewById(R.id.tv_ordershipped_frgcurrentorder);
		orderToship=(TextView) view.findViewById(R.id.tv_ordertoship_frgcurrentorder);
		orderRefunded=(TextView) view.findViewById(R.id.tv_orderrefunded_frgcurrentorder);
		orderArrived=(TextView) view.findViewById(R.id.tv_orderarrived_frgcurrentorder);
		orderToArrive=(TextView) view.findViewById(R.id.tv_ordertoarrive_frgcurrentorder);
		orderReceived=(TextView) view.findViewById(R.id.tv_orderreceived_frgcurrentorder);
		orderToReceive=(TextView) view.findViewById(R.id.tv_ordertoreceive_frgcurrentorder);
		orderToRetake=(TextView) view.findViewById(R.id.tv_ordertoretake_frgcurrentorder);
		orderRetaked=(TextView) view.findViewById(R.id.tv_orderretaked_frgcurrentorder);
		orderAbandomed=(TextView) view.findViewById(R.id.tv_orderabandomed_frgcurrentorder);
		orderPrinted=(TextView) view.findViewById(R.id.tv_orderprinted_frgcurrentorder);
		orderToPrint=(TextView) view.findViewById(R.id.tv_ordertoprint_frgcurrentorder);
		orderToMachine =(TextView) view.findViewById(R.id.tv_ordertomachine_frgcurrentorder);
		orderMachined=(TextView) view.findViewById(R.id.tv_ordermachined_frgcurrentorder);
		prgs= (ProgressBar) view.findViewById(R.id.prgs_frg_frgcurrentorder);
	    resultHint=(TextView) view.findViewById(R.id.tv_functionresult_frg_frgcurrentorder);
		refresh=(Button) view.findViewById(R.id.btn_refresh_frg_frgcurrentorder);
		function1=(Button) view.findViewById(R.id.btn_function1_frg_frgcurrentorder);
		function2=(Button) view.findViewById(R.id.btn_function2_frg_frgcurrentorder);
		sp_machine= (Spinner) view.findViewById(R.id.sp_machine_frgcurrentorder);
		img_calendar= (ImageView) view.findViewById(R.id.img_calendar_frgcurrentorder);
	//	calendarView=(CalendarView)  view.findViewById(R.id.cv_date_frgcurrentorder);
		datePicker= (DatePicker) view.findViewById(R.id.dp_date_frgcurrentorder);
		sp_timeFlag= (Spinner) view.findViewById(R.id.sp_timeflag_frgcurrentorder);
		date= (TextView) view.findViewById(R.id.tv_date_frgcurrentorder);
		orderListView= (ListView) view.findViewById(R.id.listview_order_frgcurrentorder);
		chooseall= (CheckBox) view.findViewById(R.id.ck_chooseall_frgcurrentorder);
		lt_datePicker= (LinearLayout) view.findViewById(R.id.lt_dpdate_frgcurrentorder);
		confirmDate = (Button) view.findViewById(R.id.btn_confirmdate_frgcurrentorder);
		
		List<String> sp_timeFlagDate= new ArrayList<String> ();  sp_timeFlagDate.add("早班"); sp_timeFlagDate.add("中班");  sp_timeFlagDate.add("晚班");
		ArrayAdapter<String>	adapter= new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item,sp_timeFlagDate);
		sp_timeFlag.setAdapter(adapter);  
		sp_timeFlag.setOnItemSelectedListener(timeFlagSelectedListemer);
		
		orderListAdapter= new OrderListAdapter(getActivity());
		orderListView.setAdapter(orderListAdapter);
		
		Calendar ca= Calendar.getInstance();
		 datePicker.init(ca.get(Calendar.YEAR), ca.get(Calendar.MONTH), ca.get(Calendar.DAY_OF_MONTH),
	        		new DatePicker.OnDateChangedListener() {
						
						@Override
						public void onDateChanged(DatePicker view, int year, int monthOfYear,
								int dayOfMonth) {
							date.setText("日期："+year+"-"+(monthOfYear+1)+"-"+dayOfMonth);
							searchOrderJO.put(Order.DATEAA, DateTimeFunction.myDateFormat(year, monthOfYear , dayOfMonth));
						//	pullCurrentOrder();						
						}
					});
	   sp_machine.setOnItemSelectedListener(machineSelectedListener);
	  
	   chooseall.setOnCheckedChangeListener(new OnCheckedChangeListener() {	
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			for(int i=0;i<ordersJA.getJSONArray(COCid).size();i++){
				ordersJA.getJSONArray(COCid).getJSONObject(i).put(ISSELECTED, isChecked);
				orderListAdapter.notifyDataSetChanged();
			}
			
		}
	});
	   
	   orderAll.setOnClickListener(myClickListenr);
	   orderCanceled.setOnClickListener(myClickListenr);
	   orderPayid.setOnClickListener(myClickListenr);
	   orderToPay.setOnClickListener(myClickListenr);
	   orderAccepted.setOnClickListener(myClickListenr);
	   orderToAccept.setOnClickListener(myClickListenr);
	   orderRefused.setOnClickListener(myClickListenr);
	   orderShiped.setOnClickListener(myClickListenr);
	   orderToship.setOnClickListener(myClickListenr);
	   orderRefunded.setOnClickListener(myClickListenr);
	   orderArrived.setOnClickListener(myClickListenr);
	   orderToArrive.setOnClickListener(myClickListenr);
	   orderReceived.setOnClickListener(myClickListenr);
	   orderToReceive.setOnClickListener(myClickListenr);
	   orderToRetake.setOnClickListener(myClickListenr);
	   orderRetaked.setOnClickListener(myClickListenr);
	   orderAbandomed.setOnClickListener(myClickListenr);
	   orderPrinted.setOnClickListener(myClickListenr);
	   orderToPrint.setOnClickListener(myClickListenr);
	   orderToMachine.setOnClickListener(myClickListenr);
       orderMachined.setOnClickListener(myClickListenr);
	   refresh.setOnClickListener(myClickListenr);
	   function1.setOnClickListener(myClickListenr);
	   function2.setOnClickListener(myClickListenr);	
	   img_calendar.setOnClickListener(myClickListenr);
	   confirmDate.setOnClickListener(myClickListenr);
	 
	}
	private  void clearAllOrderClassifySelected(){
		orderAll.setBackgroundResource(R.xml.style_blueborder_whitebg); 
		orderCanceled.setBackgroundResource(R.xml.style_blueborder_whitebg);
		orderPayid.setBackgroundResource(R.xml.style_blueborder_whitebg);
		orderToPay.setBackgroundResource(R.xml.style_blueborder_whitebg);
		orderAccepted.setBackgroundResource(R.xml.style_blueborder_whitebg);
		orderToAccept.setBackgroundResource(R.xml.style_blueborder_whitebg);
		orderRefused.setBackgroundResource(R.xml.style_blueborder_whitebg);
		orderToMachine.setBackgroundResource(R.xml.style_blueborder_whitebg);
		orderMachined.setBackgroundResource(R.xml.style_blueborder_whitebg);
		orderShiped.setBackgroundResource(R.xml.style_blueborder_whitebg);
		orderToship.setBackgroundResource(R.xml.style_blueborder_whitebg);
		orderRefunded.setBackgroundResource(R.xml.style_blueborder_whitebg);
		orderArrived.setBackgroundResource(R.xml.style_blueborder_whitebg);
		orderToArrive.setBackgroundResource(R.xml.style_blueborder_whitebg);
	    orderReceived.setBackgroundResource(R.xml.style_blueborder_whitebg);
	    orderToReceive.setBackgroundResource(R.xml.style_blueborder_whitebg);
	    orderToRetake.setBackgroundResource(R.xml.style_blueborder_whitebg);
	    orderRetaked.setBackgroundResource(R.xml.style_blueborder_whitebg);
	    orderAbandomed.setBackgroundResource(R.xml.style_blueborder_whitebg);
		orderPrinted.setBackgroundResource(R.xml.style_blueborder_whitebg);;
		orderToPrint.setBackgroundResource(R.xml.style_blueborder_whitebg);
	}
	
	class OrderListAdapter extends BaseAdapter {
		   
		
	    private LayoutInflater layoutInflater;  
	    private Context context;  
	    
	   public OrderListAdapter(Context context) {
			super();
			
			this.context = context;
		    this.layoutInflater=LayoutInflater.from(context); 
		}


	  final class Zujian{  
	    public TextView orderId,orderState,refund,dateTimeAA,address,product;  
	    public  Button  see;
	    public CheckBox choose;
	   
	  }   //end of Zujian

	      @Override 
	    public int getCount() {
		// TODO Auto-generated method stub
	    	  if(isOrderListVailble) 
		  {return ordersJA.getJSONArray(COCid).size();
		 }else{  return 0;}
		  
	}

	   @Override
	  public Object getItem(int position) {
		// TODO Auto-generated method stub
		 return ordersJA.getJSONArray(COCid).getJSONObject(position);  
	}

	  @Override
	  public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position; 
	}

	  @Override
	  public View getView(int position, View  convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final int selectID = position;   
		 Zujian zj=null;  
	        if(convertView==null){  
	            zj=new Zujian();  
	            //获得组件，实例化组件  
	            convertView=layoutInflater.inflate(R.layout.list_order_frgcurrentorder, null);    
	            zj.orderId=(TextView) convertView.findViewById(R.id.tv_id_listorder_frgcurrentorder);
	            zj.orderState=(TextView) convertView.findViewById(R.id.tv_state_listorder_frgcurrentorder);
	            zj.refund=(TextView) convertView.findViewById(R.id.tv_refund_listorder_frgcurrentorder);
	            zj.dateTimeAA=(TextView) convertView.findViewById(R.id.tv_datetimeaa_listorder_frgcurrentorder);
	            zj.address=(TextView) convertView.findViewById(R.id.tv_address_listorder_frgcurrentorder);
	            zj.product=(TextView) convertView.findViewById(R.id.tv_product_listorder_frgcurrentorder);
	            zj.see= (Button) convertView.findViewById(R.id.btn_see_listorder_frgcurrentorder);
	            zj.choose= (CheckBox) convertView.findViewById(R.id.ck_choose_listorder_frgcurrentorder);
	            convertView.setTag(zj);  
	            System.out.println("position----"+selectID+"------inflated");
	        }else{   System.out.println("position----"+selectID+"-------not inflated");
	            zj=(Zujian)convertView.getTag();  
	        }  			  
	        //绑定数据  
	        JSONObject record=ordersJA.getJSONArray(COCid).getJSONObject(selectID);
	       
	        zj.orderId.setText(""+record.getLong(Order.ID));
	        zj.orderState.setText(CommonFunction.spellOrderStateWord(record.getInt(Order.STATE)));
	        zj.address.setText(record.getString(Order.MACHINEADDRESS));
	        String dateTimeAA=record.getString(Order.DATETIMEAA);        
	        try {String wordDateTimeAA=DateTimeFunction.transWordDateFormat(dateTimeAA);
	        	zj.dateTimeAA.setText(wordDateTimeAA);
			} catch (Exception e) {e.printStackTrace();	}
	       if(record.getInt(Order.ISREFUND)==1){
	    	 zj.refund.setText("无退款");  
	       }else{
	    	  // record.getJSONObject("refund") 
	    	   zj.refund.setText("有退款");  
	       }
	       String products="";
	       for(int i=0;i<record.getJSONArray("products").size();i++){
	    	   JSONObject productJO=record.getJSONArray("products").getJSONObject(i);
	    	   products+="  "+productJO.getString(OrderProduct.PRODUCTNAME);
	    	   products+="  "+productJO.getString(OrderProduct.BRANCHNAME);
	    	   products+="  "+productJO.getString(OrderProduct.BRANCHNUM)+"份";
	    	  if(i!=record.getJSONArray("products").size()-1){  products+="\n";}
	       }
	       zj.product.setText(products);
	     
	       zj.choose.setChecked(record.getBoolean(ISSELECTED));
	       zj.choose.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			        CheckBox choose=(CheckBox) v;
			        ordersJA.getJSONArray(COCid).getJSONObject(selectID).put(ISSELECTED, choose.isChecked());  
			}
		   });
	       
	       zj.see.setOnClickListener(new View.OnClickListener() {			
				@Override
				public void onClick(View v) {
					Message msg = new Message();               
                   msg.what=2;
                  msg.arg1=1; //订单管理
                  msg.arg2=5;  //订单详情
                 Bundle bundle= new Bundle(); 
                 bundle.putString("order", ordersJA.getJSONArray(COCid).getJSONObject(selectID).toString());
                 bundle.putString("tag","order_id_="+ordersJA.getJSONArray(COCid).getJSONObject(selectID).getLong(Order.ID));
                 bundle.putString("title","订单"+ordersJA.getJSONArray(COCid).getJSONObject(selectID).getLong(Order.ID));
                 msg.obj=bundle;
                 SupplierMainActivity.myMainHandler.sendMessage(msg);					
				}
			}); 
	       
	        return convertView;
	       } 
	  }// end Adapter
	
	
	  private  class HttpPostTaskforPollCurrentOrder extends android.os.AsyncTask<String,String,Map<String,Object>>{
			@Override
			protected Map<String,Object> doInBackground(String... params) {
				// TODO Auto-generated method stub
				 Map<String,Object> map = new HashMap<String ,Object>();		
			  map =	UniversalHttpPost.doPost(params);	             
				return map;
			}
			
			@Override
			protected void onPostExecute(Map<String,Object> map) {
			
				 prgs.setVisibility(View.INVISIBLE);	
			/*	 Message msg= new Message();
				 msg.what=1;
			    CustomerMainActivity.mainHandler.sendMessage(msg); 
				  */
				 System.out.println("-----------onPostExecute()--------------");
				 String PostResult=(String) map.get("PostResult");		 
				 boolean networkstate=(Boolean) map.get("PostState");
				 if(!networkstate){
					 resultHint.setText("操作结果：无法连接服务器");
			               return; }
				//	Toast.makeText(getActivity(), "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
					Boolean ActionStatus=false;
					String ErrorInfo="";
					JSONObject json = null;
					String affairOnPost="";
					try{
				     json= JSONObject.fromObject(PostResult);
					 ActionStatus=json.getBoolean("success");
					 ErrorInfo=json.getString("errorInfo");	
					 resultHint.setText("ErrorInfo");
					 affairOnPost= json.getString("affair");
					}catch(JSONException e){
						resultHint.setText("操作结果：回传数据解析错误");
						  return;}	
					
			       if(!ActionStatus){ resultHint.setText("操作结果："+ErrorInfo); return;  } 	
			      
			     if(affairOnPost.equals(PULLCURRENTORDER)){
			    	 JSONArray ordersONline=json.getJSONArray("orders");
			    	 if(ordersONline.size()==0) {resultHint.setText("搜索成功，但是并无满足条件的订单"); 
			    	 }else{ resultHint.setText("搜索成功"); }
			    	 classifyOrder(ordersONline);
	 	                   }
			     
			     if(affairOnPost.equals(ACCEPTORDER)||affairOnPost.equals(REFUSEORDER)||affairOnPost.equals(SHIPORDER)){
			    	 JSONArray ordersONline=json.getJSONArray("orders");
			    	 changeOrderState(ordersONline);
			        }
			     if(affairOnPost.equals(AFFAIR_PRINTORDER)){
			    	 JSONArray ordersONline=json.getJSONArray("orders");
			    	 for(int i=0;i<ordersONline.size();i++){
			    		  int printTimes= ordersONline.getJSONObject(i).getInt(Order.PRINTTIMES);
			    		  long id= ordersONline.getJSONObject(i).getLong(Order.ID);
			    		  for(int j=0;j<ordersJA.getJSONArray(ALL).size();j++){
			    			  if(id==ordersJA.getJSONArray(ALL).getJSONObject(j).getLong(Order.ID)){
			    				  
			    				  ordersJA.getJSONArray(ALL).getJSONObject(j).put(Order.PRINTTIMES,printTimes);
			    				  break;
			    			  }
			    		  }
			    		 
			    	  }
					  classifyOrder(ordersJA.getJSONArray(ALL)); 
			        }
			      if(affairOnPost.equals(SEARCHDISTRIBUTE)){
			    	  needPullMachine=false;
		        	   sp_machine_data.clear();
		        	   sp_machine_data.add("全部");
						JSONArray distributesJA= json.getJSONArray("distributes");		
						for (int i = 0; i <distributesJA.size(); i++) {
							JSONObject machineJO=distributesJA.getJSONObject(i).getJSONObject("MACHINE");
							sp_machine_data.add(machineJO.getString(Machine.NAME));
							array_machine_id[i+1]=machineJO.getInt(Machine.ID);					
						             }
					ArrayAdapter<String>	adapter= new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item,sp_machine_data);
						sp_machine.setAdapter(adapter);
			          	}
							
			} //onPostExecute
	} //AsyncTask
	
	  private void classifyOrder(JSONArray ordersJAOnline){
		  isOrderListVailble=false;
		  ordersJA.clear();
		  for(int i=0;i<21;i++){
			ordersJA.add(new JSONArray());  
		  }
		  boolean isNeedPrint=false;
		  for(int i=0;i<ordersJAOnline.size();i++){
			  JSONObject jo=ordersJAOnline.getJSONObject(i);
			  jo.put(ISSELECTED, false);
			  int state=jo.getInt(Order.STATE);
			  
			  ordersJA.getJSONArray(ALL).add(jo);
			  
			  if(state==3||state==4||state==6){
				  ordersJA.getJSONArray(CANCELED).add(jo);
			  }
			  
			  if(jo.getInt(Order.ISMONEYPAID)==2){ ordersJA.getJSONArray(PAID).add(jo); }
			  if(state==1){
				  ordersJA.getJSONArray(TOPAY).add(jo);
			  }
			  if(state==5){
				  ordersJA.getJSONArray(REFUSED).add(jo);
			  }
			  if(state==10){
				  ordersJA.getJSONArray(TOACCEPT).add(jo);
			  }
			  if(state>=11){
				  ordersJA.getJSONArray(ACCEPTED).add(jo);
				  isNeedPrint=true;
			  }
			 
			  if(state==11){
				  ordersJA.getJSONArray(TOMACHINE).add(jo); 
			  }
			  if(state>=12){
				  ordersJA.getJSONArray(MACHINED).add(jo);
			  }
			  if(state==12){
				  ordersJA.getJSONArray(TOSHIP).add(jo);
			  }
			  if(state>=20){
				  ordersJA.getJSONArray(SHIPED).add(jo);
			  }
			  if(state==20){
				  ordersJA.getJSONArray(TOARRIVE).add(jo);
			  }
			  if(state>=21){
				  ordersJA.getJSONArray(ARRIVED).add(jo);
			  }
			long datimetl=Long.parseLong(jo.getString(Order.DATETIMETL));	
			long datimenow=Long.parseLong(DateTimeFunction.getMyDateTime(0));
			
			  if(state==21&&datimetl>datimenow){
				  ordersJA.getJSONArray(TORECEIVE).add(jo);
			  }
			  if(state==21&&datimetl<datimenow){
				  ordersJA.getJSONArray(TORETAKE).add(jo);
			  }
			  if(state==22){
				  ordersJA.getJSONArray(RECEIVED).add(jo);
			  }
			  if(state==23){
				  ordersJA.getJSONArray(RETAKED).add(jo);
			  }
			  if(state==24){
				  ordersJA.getJSONArray(ABANDOMED).add(jo);
			  }
			 
			  if(isNeedPrint&&jo.getInt(Order.PRINTTIMES)==0){
				  ordersJA.getJSONArray(TOPRINT).add(jo);
				  System.out.println("printTimes="+jo.getInt(Order.PRINTTIMES));
			  }
			  if(jo.getInt(Order.PRINTTIMES)!=0){
				  ordersJA.getJSONArray(PRINTED).add(jo);  
				  System.out.println("printTimes="+jo.getInt(Order.PRINTTIMES));
			  }
			  
		  }	 		  
		  isOrderListVailble=true;		
		  countOrderClassifyNum();
	  }
	  
	  private void changeOrderState(JSONArray ordersONline ){
		  for(int i=0;i<ordersONline.size();i++){
    		  int state= ordersONline.getJSONObject(i).getInt(Order.STATE);
    		  long id= ordersONline.getJSONObject(i).getLong(Order.ID);
    		  for(int j=0;j<ordersJA.getJSONArray(ALL).size();j++){
    			  if(id==ordersJA.getJSONArray(ALL).getJSONObject(j).getLong(Order.ID)){
    				  ordersJA.getJSONArray(ALL).getJSONObject(j).put(Order.STATE, state);
    				  break;
    			  }
    		  }
    		 
    	  }
		  classifyOrder(ordersJA.getJSONArray(ALL)); 
	  }
	  private  void countOrderClassifyNum(){
		  orderAll.setText("全部"+ordersJA.getJSONArray(ALL).size());
		  orderCanceled.setText("已取消"+ordersJA.getJSONArray(CANCELED).size());
		  orderPayid.setText("已支付"+ordersJA.getJSONArray(PAID).size());
		  orderToPay.setText("待支付"+ordersJA.getJSONArray(TOPAY).size());
		  orderRefused.setText("已据单"+ordersJA.getJSONArray(REFUSED).size());
		  orderAccepted.setText("已接单"+ordersJA.getJSONArray(ACCEPTED).size());
		  orderToAccept.setText("待接单"+ordersJA.getJSONArray(TOACCEPT).size());
		  orderToMachine.setText("柜未认"+ordersJA.getJSONArray(TOMACHINE).size());
		  orderMachined.setText("柜已认"+ordersJA.getJSONArray(MACHINED).size());
		  orderShiped.setText("已发货"+ordersJA.getJSONArray(SHIPED).size());
		  orderToship.setText("待发货"+ordersJA.getJSONArray(TOSHIP).size());
		  orderArrived.setText("已送到"+ordersJA.getJSONArray(ARRIVED).size());
		  orderToArrive.setText("待送达"+ordersJA.getJSONArray(TOARRIVE).size());
		  orderReceived.setText("已取货"+ordersJA.getJSONArray(RECEIVED).size());
		  orderToRetake.setText("待回收"+ordersJA.getJSONArray(TORETAKE).size());
		  orderToReceive.setText("待取货"+ordersJA.getJSONArray(TORECEIVE).size());
		  orderAbandomed.setText("已抛弃"+ordersJA.getJSONArray(ABANDOMED).size());
		  orderRetaked.setText("已回收"+ordersJA.getJSONArray(RETAKED).size());
		  orderToPrint.setText("待打印"+ordersJA.getJSONArray(TOPRINT).size());
		  orderPrinted.setText("已打印"+ordersJA.getJSONArray(PRINTED).size());
	  }
	  
}
